package com.flyqiu.flow.starter;


import com.flyqiu.flow.api.event.FlowEngineEvent;
import com.flyqiu.flow.api.script.IVariableScope;
import com.flyqiu.flow.core.script.DefaultJuelFlyQiuFlowScriptActuator;
import com.flyqiu.flow.starter.el.SpringApplicationContextElResolver;
import com.flyqiu.flow.starter.el.SpringBeanReadOnlyELResolver;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import javax.el.CompositeELResolver;
import java.util.HashMap;
import java.util.Map;


public class FlyQiuFlowSpringJuelFlyQiuFlowScriptActuator extends DefaultJuelFlyQiuFlowScriptActuator implements ApplicationContextAware, FlowEngineEvent {

    private final ApplicationContext applicationContext;


    private SpringBeanReadOnlyELResolver beanReadOnlyELResolver = null;

    public FlyQiuFlowSpringJuelFlyQiuFlowScriptActuator(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;

    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {

        Map<String, Object> beanMap = new HashMap<>();
        String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames();
        for (String beanName : beanDefinitionNames) {
//            System.out.println("bean:" + beanName);
            beanMap.put(beanName, null);
        }
        beanReadOnlyELResolver = new SpringBeanReadOnlyELResolver(applicationContext, beanMap);
        defaultElResolver.add(beanReadOnlyELResolver);
    }

    @Override
    public CompositeELResolver createElResolver(IVariableScope scope) {
        CompositeELResolver defaultElResolver = super.createElResolver(scope);
        if (beanReadOnlyELResolver != null) {
            return defaultElResolver;
        }
        SpringApplicationContextElResolver springApplicationContextElResolver = new SpringApplicationContextElResolver(applicationContext);
        defaultElResolver.add(springApplicationContextElResolver);
        return defaultElResolver;
    }
}
